package org.west.sky.scripture.exports.core;

import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: chz
 * @date: 2023/9/18
 * @description: 优先采用@ColumnWidth设置的宽度，未设置则采用自适应宽度
 */
public class FixedMatchColumnWidthStyleStrategy extends LongestMatchColumnWidthStyleStrategy {

    private static final int MAX_COLUMN_WIDTH = 30;

    private final Map<Integer, Map<Integer, Integer>> cache = MapUtils.newHashMapWithExpectedSize(8);

    @Override
    protected void setColumnWidth(CellWriteHandlerContext context) {
        WriteSheetHolder writeSheetHolder = context.getWriteSheetHolder();
        Cell cell = context.getCell();
        Boolean isHead = context.getHead();
        List<WriteCellData<?>> cellDataList = context.getCellDataList();
        boolean needSetWidth = context.getHead() || !CollectionUtils.isEmpty(cellDataList);
        if (!needSetWidth) {
            return;
        }
        //自定列宽
        ExcelContentProperty excelContentProperty = context.getExcelContentProperty();
        Field field = excelContentProperty.getField();
        ColumnWidth width = null;
        if (null != field) {
            width = field.getAnnotation(ColumnWidth.class);
        }
        if (null != width) {
            writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), width.value() * 256);
            return;
        }
        //默认自适应列宽
        setColumnWidth2(writeSheetHolder, cellDataList, cell, context.getHeadData(), context.getRelativeRowIndex(), isHead);
    }


    private void setColumnWidth2(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell,
                                  Head head,
                                  Integer relativeRowIndex, Boolean isHead) {
        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
        if (!needSetWidth) {
            return;
        }
        Map<Integer, Integer> maxColumnWidthMap = cache.computeIfAbsent(writeSheetHolder.getSheetNo(), key -> new HashMap<>(16));
        Integer columnWidth = dataLength(cellDataList, cell, isHead);
        if (columnWidth < 0) {
            return;
        }
        if (columnWidth > MAX_COLUMN_WIDTH) {
            columnWidth = MAX_COLUMN_WIDTH;
        }
        Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
        if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
            maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
            writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
        }
    }

    private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
        if (isHead) {
            return cell.getStringCellValue().getBytes().length;
        }
        WriteCellData<?> cellData = cellDataList.get(0);
        CellDataTypeEnum type = cellData.getType();
        if (type == null) {
            return -1;
        }
        switch (type) {
            case STRING:
                return cellData.getStringValue().getBytes().length;
            case BOOLEAN:
                return cellData.getBooleanValue().toString().getBytes().length;
            case NUMBER:
                return cellData.getNumberValue().toString().getBytes().length;
            default:
                return -1;
        }
    }
}
